package em.util;

import base.cache.CacheManager;
import base.jfinal.plugin.ClassSearcher;
import base.util.PropertiesContent;
import com.jfinal.kit.StrKit;

import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * Package name is em.util
 * Created by gaby
 * Create time is 2016-3-17 14:30
 * 从数据库中取得数据存放到内存中
 */
public class GlobalConfig {
    private static GlobalConfig globalConfig=new GlobalConfig();
    public static GlobalConfig getInstance(){
        return globalConfig;
    }

    /**
     * 需要从数据库里初始化的配置数据
     */
    public void init(){

    }



    /**
     * 初始化从配置文件里的数据
     */
    public void initProp(){
        //初始化db.properties
        initProperties();

        //初始化sql语句
        initSql();
    }

    /**
     * 重新所有设置
     */
    public void reset(){
        initProp();
        init();
    }

    /**
     * 初始化db.properties
     */
    private void initProperties(){
        Map<String, Object> config = new HashMap<String, Object>();
        ResourceBundle rb = ResourceBundle.getBundle("db");
        Enumeration<String> cfgs = rb.getKeys();
        while (cfgs.hasMoreElements()) {
            String key = cfgs.nextElement();
            String val=rb.getString(key);
            config.put(key,val);
        }
        CacheManager.getInstance().put(ConstUtil.CACHE_KEY_PROPERTIES,config);
    }

    /**
     * 初始化sql语句
     */
    public void initSql(){
        //初始化Map
        Map<String, String> mapSql=new HashMap<String, String>();
        BufferedReader br;
        String temp,strSqlKey="";
        LinkedList<String> list = new LinkedList<String>();

        try{
            //取得文件名和文件流
            Map<String, FileInputStream> ins = getFile();
            for (Map.Entry<String, FileInputStream> entry:ins.entrySet()){
                br=new BufferedReader(new InputStreamReader(entry.getValue(),"UTF-8"));
                list.clear();
                while ((temp = br.readLine()) != null) {
                    if(StrKit.isBlank(temp)) continue;//如果取得空，则继续循环

                    //如果---，则取得sql
                    if(temp.trim().startsWith("---")){
                        strSqlKey=entry.getKey()+"."+list.pollFirst();
                    }else if(temp.trim().startsWith("===")){
                        mapSql.put(strSqlKey, getSqlToStr(list));
                        list.clear();
                    }else{
                        list.addLast(temp);
                    }
                }
                if(list.size()>0){
                    mapSql.put(strSqlKey, getSqlToStr(list));
                }
            }
        }catch(Exception ex){
            System.out.println("初始化sql失败："+ex.getMessage());
        }

        //取得sql语句,保存到内存中
        CacheManager.getInstance().put(ConstUtil.CACHE_KEY_GLOBAL_SQL,mapSql);
    }

    /**
     * 将列表数据转换成string
     * @param ls
     * @return
     */
    private String getSqlToStr(LinkedList<String> ls){
        StringBuffer strReturn=new StringBuffer();
        String lineSeparator = System.getProperty("line.separator", "\n");
        for (String string : ls) {
            strReturn.append(string).append(lineSeparator);
        }
        return strReturn.toString();
    }

    /**
     * 取得sql语句所在的文件
     * @return
     */
    private Map<String, FileInputStream> getFile() {
        Map<String,FileInputStream> mp=new HashMap<String, FileInputStream>();
        String prefix;
        URL URL=ClassSearcher.class.getResource(PropertiesContent.get("sql.root")+"/");
        File file=new File(URL.getFile());
        for(File f: file.listFiles()){
            prefix=f.getName().substring(f.getName().indexOf(".")+1);
            if(prefix.toLowerCase().intern()=="md".intern()||prefix.toLowerCase().intern()=="sql".intern()){
                try {
                    mp.put(f.getName().replace("."+prefix, ""), new FileInputStream(f));
                } catch (FileNotFoundException e) {
                }
            }
        }
        return mp;
    }
}
